<template>
  <div>
    <back></back>
    <form-back height="280px">
      <public-form-body ref="login_form" :user="user" :rules="rules">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" autocomplete="off" placeholder="请输入邮箱" clearable/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" type="password" placeholder="请输入密码" show-password clearable/>
        </el-form-item>
        <div id="button">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="primary" @click="resetForm">重置</el-button>
        </div>
        <el-link id="to-another-form" :underline="false" type="primary"
                 @click="$router.push('/register')">没有账号？去注册
        </el-link>
      </public-form-body>
    </form-back>
  </div>
</template>

<script>
import {login} from "../util/request/user";
import {encrypt} from "../util/encrypt";
import {message} from "../util/message";
import axios from "../axios";
import Back from "../components/back";
import FormBack from "../components/form-back";
import PublicFormBody from "../components/public-form-body";

export default {
  name: "login",
  components: {PublicFormBody, FormBack, Back},
  data() {
    return {
      user: {
        email: '',
        password: '',
      },
      rules: {
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 8, max: 20, message: '密码长度 8 到 20 位', trigger: 'blur'}
        ],
      },
    }
  },
  methods: {
    resetForm() {
      this.$refs.login_form.resetFields();
    },
    login() {
      login({
        email: this.user.email,
        password: encrypt(this.user.password)
      }).then(res => {
        this.$message(message(res.data.success, res.data.msg))
        if (res.data.success) {
          let token = res.headers[axios.$TOKEN_HEADER]
          localStorage.setItem('token', token)
          localStorage.setItem('username', res.data.data.name)
          this.$router.push({name: 'record'})
        }
      })
    },
  }
}
</script>

<style scoped>
</style>
